/// <reference path="../../apicloud.d.ts" />

const vm = new Vue({
    el: '#main',
    data: {
        galleryList: [],
        city: [],
        searchBtn: true,
    },
    methods: {
        goPages,
        reqCityHouseList,
        fxiImg,
    },
    components: {},
});

if (fxj.deBug) {
    main();
}

function main() {
    let tmId = null;
    document.body.addEventListener('touchmove', () => {
        if (tmId) clearTimeout(tmId);
        tmId = setTimeout(() => {
            canShowImg();
        }, 200);
    });
    if (!isIpad() && (getAndroidVersion() >= 5 || getIosVersion() >= 9)) {
        initSearchBtnAnime();
    }
    const bannerElement = document.getElementById('banner');
    const height = document.body.clientWidth * .666667 + 'px';
    bannerElement.style.maxHeight = height;
    bannerElement.style.minHeight = height;
    getRecommend().catch(
        e => {
            console.error(e);
        },
    );
}

function apiready() {
    main();
    setCustomRefreshHeaderInfo(() => {
        vm.searchBtn = true;
        getRecommend().catch(
            e => {
                console.error(e);
            },
        );
    });
    if (!isTestVersion() && api.appVersion !== '0.0.0') {
        checkUpdate();
    }
}

async function getRecommend() {
    const res = await ajax({
        url: 'home/index/getRecommend',
        type: 'get',
    });
    if (res.err !== 0) {
        toast(res.msg);
        return;
    }
    vm.city = res.data;
    setTimeout(() => {
        setHouseImgHeight();
        canShowImg();
    }, 0);
}

async function reqCityHouseList(cityId) {
    const close = fxj.dialog.loading({
        noBg: true,
    });
    const result = await ajax({
        url: 'home/search/search',
        type: 'POST',
        data: {
            code: cityId,
            search: '',
            type: 1,
        },
    });
    if (result.err !== 0) {
        mui.toast(result.msg);
        return;
    }
    close();
    goPage(`house_res_list.html`, {
        localData: {
            searchHouseList: result.data,
            cityId: +cityId,
        },
    });
}

function checkUpdate() {
    const mam = api.require('mam');
    mam.checkUpdate(function (ret) {
        if (ret) {
            const {
                update,
                closed,
                version,
                updateTip,
                time,
                source,
            } = ret.result;
            if (update === true && closed === false) {
                const str = `
有新版本啦:${version}

更新信息:
${updateTip}

发布时间:${time}
`.trim();
                api.alert({
                    title: '有分享家新版本，请更新。',
                    msg: str,
                    buttons: ['立即更新'],
                }, function () {
                    if (api.systemType === 'android') {
                        api.download({
                            url: source,
                            report: true,
                        }, function (ret) {
                            const {
                                state,
                                percent,
                                savePath,
                            } = ret;
                            if (ret && 0 === +state) { /* 下载进度 */
                                api.toast({
                                    msg: '正在下载应用' + percent + '%',
                                    duration: 2000,
                                });
                            }
                            if (ret && 1 === +state) { /* 下载完成 */
                                api.installApp({
                                    appUri: savePath,
                                });
                            }
                        });
                    }
                    if (api.systemType === 'ios') {
                        api.installApp({
                            appUri: source,
                        });
                    }
                });
            }
        }
    });
}

function initSearchBtnAnime() {
    let startPointY = 0;
    let endPointY = 0;
    document.documentElement.addEventListener('touchstart', e => {
        startPointY = e.changedTouches[0].clientY;
    });
    document.documentElement.addEventListener('touchend', e => {
        endPointY = e.changedTouches[0].clientY;
        if (startPointY - endPointY < -30) {
            vm.searchBtn = true;
        } else if (startPointY - endPointY > 50) {
            vm.searchBtn = false;
        }
    });
}

function fxiImg(src) {
    return fxj.fixImgUrl(src);
}

function setHouseImgHeight() {
    const imgs = document.querySelectorAll('.house-img');
    forEach(imgs, img => {
        const height = img.clientWidth / 3 * 2;
        img.style.minHeight = height + 'px';
        img.style.maxHeight = height + 'px';
    });
}

function goPages(page, options) {
    const close = fxj.dialog.loading();
    setTimeout(() => {
        close();
    }, 3000);
    goPage(page, options);
}

function canShowImg() {
    const divList = document.querySelectorAll('div[data-url]');
    forEach(divList, div => {
        div.style.backgroundImage = `url(${div.getAttribute('data-url')})`;
        div.removeAttribute('data-url');
    });
}